package com.tbq.game.service.http

import com.alibaba.fastjson.JSON
import com.tbq.game.service.utils.L
import com.yanzhenjie.kalle.Response
import com.yanzhenjie.kalle.simple.Converter
import com.yanzhenjie.kalle.simple.SimpleResponse
import java.lang.reflect.Type

class JsonConverter : Converter {
    override fun <S : Any?, F : Any?> convert(
        succeed: Type?,
        failed: Type?,
        response: Response?,
        fromCache: Boolean
    ): SimpleResponse<S, F> {
        val code = response?.code() ?: 0
        val serverJson = response?.body()?.string()
        var data: S? = null
        var failed: F? = null
        when (code) {
            in 200..299 -> try {
                data = when (succeed) {
                    String::class.javaObjectType -> serverJson as S
                    else -> JSON.parseObject(serverJson, succeed)
                }
                L.e("请求结果：$serverJson", "HTTP")
            } catch (e: Exception) {
                failed = "数据解析出错!" as F
                L.e("解析出错：$serverJson", "HTTP")
            }
            in 400..499 -> // 客户端请求不符合服务端要求。
                failed = "发生未知异常" as F
            else -> failed = "服务器开小差啦!" as F
        }
        return SimpleResponse.newBuilder<S, F>().code(code).headers(response?.headers()).fromCache(fromCache)
            .succeed(data).failed(failed).build()

    }
}